package com.leyou.cart.interceptor;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties properties;

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cookie中获取token信息
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
        // 判断token是否为null
        if(StringUtils.isBlank(token)){
            // 重定向到登录页面
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
        }

        try {
            // 解析token
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());

            // 保存到线程变量
            THREAD_LOCAL.set(userInfo);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
        }
        return false;
    }

    public static UserInfo get(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放线程变量
        THREAD_LOCAL.remove();
    }
}
